package com.blog.user.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.user.entity.UserCollection;
import com.blog.user.service.UserCollectionService;
import com.blog.utils.JWTUtils;
import com.blog.utils.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zw
 * @since 2021-12-08
 */
@RestController
@RequestMapping("/userCollection")
@Slf4j
@CrossOrigin("*")
public class UserCollectionController {
    @Autowired
    UserCollectionService userCollectionService;

    //根据用户Id查询其收藏列表
    @GetMapping("/getUserCollectionByUserId/{id}/{page}/{limit}")
    public ResponseResult getUserCollectionByUserId(@PathVariable String id,@PathVariable long page,@PathVariable long limit,
                                                    String username, @RequestHeader String token){
        if(!JWTUtils.checkToken(username, token)){
            return ResponseResult.error().message("检测到用户未登录或登录信息已过期，请登录后再进行操作");
        }
        Page<UserCollection> pageInfo=new Page<>(page,limit);
        userCollectionService.pageQuery(pageInfo,id);
        List<UserCollection> collectList=pageInfo.getRecords();
        long total=pageInfo.getTotal();
        log.info(id+"获取了收藏列表"+"第"+page+"页");
        return ResponseResult.ok().data("total",total).data("collectList",collectList);
    }
    //增加用户收藏
    @PostMapping("/insertCollection")
    public ResponseResult insertCollection(String userId,Integer articleId,String username, @RequestHeader String token){
        userCollectionService.insertCollection(userId,articleId);
        log.info(userId + "收藏了"+articleId);
        return ResponseResult.ok();
    }

    //取消用户收藏
    @PostMapping("/deleteUserCollection")
    public ResponseResult deleteUserCollection(UserCollection userCollection,String username, @RequestHeader String token){
        if(!JWTUtils.checkToken(username, token)){
            return ResponseResult.error().message("检测到用户未登录或登录信息已过期，请登录后再进行操作");
        }
        userCollectionService.removeById(userCollection);
        log.info("关注表中"+userCollection.getId().toString()+"被删除了");
        return ResponseResult.ok();
    }

    //查询是否已经收藏
    @GetMapping("/isCollected/{userId}/{articleId}")
    public ResponseResult isCollected(@PathVariable  String userId,@PathVariable Integer articleId,
                                      String username, @RequestHeader String token){
        if(!JWTUtils.checkToken(username, token)){
            return ResponseResult.error().message("检测到用户未登录或登录信息已过期，请登录后再进行操作");
        }
        boolean bool=userCollectionService.isCollected(userId,articleId);
        log.info(userId+"是否收藏了"+articleId+":"+bool);
        return ResponseResult.ok().data("isCollected",bool);

    }

}

